import {
  index,
  modelOptions,
  prop,
  getModelForClass,
  plugin,
} from '@typegoose/typegoose'
import { Types } from 'mongoose'
import { ApiProperty, PickType } from '@nestjs/swagger'
import { AutoIncrementID } from '@typegoose/auto-increment'
import { Length, IsNotEmpty, IsString } from 'class-validator'

@plugin(AutoIncrementID, { field: 'userId', startAt: 1 })
@index({ username: 1 }, { unique: true })
@modelOptions({
  schemaOptions: {
    timestamps: true, //自动添加时间戳
    collection: 'users', // 设置集合名称
  },
})
export class UserClass {
  @prop()
  public readonly userId: number

  @prop({ required: true, unique: true })
  @IsNotEmpty({ message: '用户名不能为空' })
  @IsString({ message: '用户名必须为字符串' })
  @Length(3, 20, { message: '用户名长度必须在3到20之间' })
  @ApiProperty({
    description: '用户名',
    example: 'chuz1',
    required: true,
    uniqueItems: true,
  })
  public username: string

  @prop({ required: true, select: false })
  @IsNotEmpty({ message: '用户名不能为空' })
  @Length(6, 20, { message: '密码长度必须在5到20之间' })
  @IsString({ message: '密码必须为字符串' })
  @ApiProperty({ description: '密码', example: 'Hzq741226', required: true })
  public password: string

  @prop()
  @ApiProperty({ description: '邮箱', example: '***@***.com', required: false })
  public email?: string

  @ApiProperty({
    description: '包含角色名集合',
    example: ['boss'],
    required: false,
  })
  @prop({ type: () => [String] })
  public roleNames?: string[]

  @ApiProperty({
    description: '包含角色id集合',
    example: ['123***'],
    required: false,
  })
  @prop({ type: () => [String] })
  public roleIds?: string[]

  @prop({ type: () => [String] })
  public permissionIds?: string[]

  @ApiProperty({
    description: '手机号码',
    example: '135*******',
    required: false,
  })
  @prop()
  public mobile?: string

  @ApiProperty({ description: '昵称', example: '胡*', required: false })
  @prop()
  public name?: string

  @ApiProperty({ description: '头像', required: false })
  @prop()
  public avatar?: string
}

export class UpdateUserDto extends PickType(UserClass, [
  'username',
  'name',
] as const) {}

export class bulkDelDto {
  @ApiProperty({ description: '_id数组', required: true, example: ['2333***'] })
  @prop({ type: () => [Types.ObjectId] })
  public ids: Array<Types.ObjectId>
}

export const UserModel = getModelForClass(UserClass)
